package agents

import (
	"context"
	"fmt"
	"net/http"
	"time"

	"github.com/starter-go/httpagent"

	"gitee.com/bitwormhole/mails-pnp-driver/lib/common/vo"
	"gitee.com/bitwormhole/mails-pnp-driver/lib/pnp"
)

// PNPServiceImpl ...
type PNPServiceImpl struct {

	//starter:component

	_as func(pnp.Service) //starter:as("#")

	WebClients httpagent.Clients //starter:inject("#")

	PushServiceURL string //starter:inject("${mails.pnp.agent.push2.url}")
	PushToken      string //starter:inject("${mails.pnp.agent.push2.token}")
	UserName       string //starter:inject("${mails.pnp.agent.push2.username}")
	Password       string //starter:inject("${mails.pnp.agent.push2.password}")

}

func (inst *PNPServiceImpl) _impl() pnp.Service {
	return inst
}

// Push ...
func (inst *PNPServiceImpl) Push(c context.Context, msg *vo.Message) error {

	// send to server over http

	req, err := inst.preparePushRequest(c, msg)
	if err != nil {
		return err
	}

	client := inst.WebClients.GetClient()
	resp, err := client.Execute(req)
	if err != nil {
		return err
	}

	return inst.handlePushResult(c, resp)
}

func (inst *PNPServiceImpl) preparePushRequest(c context.Context, msg *vo.Message) (*httpagent.Request, error) {
	url := inst.PushServiceURL
	body := httpagent.NewEntityWithJSON(msg)
	token := inst.PushToken
	req := &httpagent.Request{
		Context: c,
		Method:  http.MethodPost,
		URL:     url,
	}
	req.SetEntity(body)
	req.Headers.Set("token", token)
	return req, nil
}

func (inst *PNPServiceImpl) handlePushResult(c context.Context, resp *httpagent.Response) error {
	code := resp.Status
	if code != http.StatusOK {
		msg := resp.Message
		return fmt.Errorf("HTTP %s", msg)
	}
	return nil
}

// Pull ...
func (inst *PNPServiceImpl) Pull(c context.Context, timeout time.Duration) (*vo.Message, error) {
	return nil, fmt.Errorf("unsupported")
}
